package com.yn.iotxiao.sql.services.Device;

import com.alibaba.fastjson.JSONObject;
import com.yn.iotxiao.Utils.Hik.HttpAysncClientUtil;
import com.yn.iotxiao.Utils.JsonHelper;
import com.yn.iotxiao.sql.entity.Device.DeviceInfo;
import com.yn.iotxiao.sql.mapper.DeviceInfoMapper;
import io.micrometer.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Slf4j
@Service
public class DeviceInfoServiceImpl implements DeviceInfoService{

    @Autowired
    DeviceInfoMapper mapper;
    @Override
    public int insert(DeviceInfo deviceInfo) {
        return mapper.insert(deviceInfo);
    }

    @Override
    public int delete(String deviceid) {
        return mapper.delete(deviceid);
    }

    @Override
    public List<DeviceInfo> getList(String searchKey, int page, int pageSize) {
        return mapper.getList(searchKey,page,pageSize);
    }

    @Override
    public int getTotal(String searchKey) {
        return mapper.getTotal(searchKey);
    }

    @Override
    public List<DeviceInfo> getWithType(int type) {
        return mapper.getWithType(type);
    }

    @Override
    public String startEventSubscribe() {

        List<DeviceInfo> devices = mapper.getWithType(2);
        if (devices.size() == 0) {
            throw new RuntimeException("没有需要订阅的设备");
        }
        for (DeviceInfo device:
             devices) {
            log.info("订阅设备事件："+device.getName());
            HttpAysncClientUtil.HttpAysncInit(device.getLoginId(),device.getPassword());
            log.info("设备用户名："+device.getLoginId());
            HttpAysncClientUtil.LonLink(String.format("http://%s/ISAPI/Event/notification/alertStream",device.getIp()),"all",false);
        }
        return "订阅成功";
    }

    @Override
    public JSONObject createDeviceWithserialnumber(String serialnumber) throws Exception{

        DeviceInfo deviceInfo = mapper.getWithserialnumber(serialnumber);
        if (deviceInfo == null || StringUtils.isBlank(deviceInfo.getDeviceid())) {
            throw new Exception("未找到对应的设备信息");
        }

        return JsonHelper.create("deviceId",deviceInfo.getDeviceid(),"deviceName",deviceInfo.getName(),
                "deviceModel",deviceInfo.getModel(),"deviceSerial",deviceInfo.getSerialnumber(),"status",deviceInfo.getStatus());
    }

    @Override
    public List<DeviceInfo> getListWithSerial(List<String> numbers) {
        return mapper.getListWithSerial(numbers);
    }

    @Override
    public DeviceInfo getWithKey(String deviceid) {
        return mapper.getWithKey(deviceid);
    }
}
